package com.crane.oss.school.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.crane.common.core.exception.BizException;
import com.crane.oss.api.bean.resp.SchoolAreaResp;
import com.crane.oss.school.syn.SynXunfeiService;
import com.crane.oss.sports.XunFeiPushEventApiService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.SysException;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.school.bean.request.QueryAreaReq;
import com.crane.oss.school.bean.request.area.AddAreaReq;
import com.crane.oss.school.bean.request.area.UpdateAreaReq;
import com.crane.oss.school.bean.resp.AreaResp;
import com.crane.oss.school.dao.AreaDao;
import com.crane.oss.school.model.Area;
import com.crane.oss.school.service.AreaService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhenxing.pi
 * @email ccsu123456@qq.com
 * @date 2022年03月26日 14时24分54秒
 */
@Service
@Slf4j
public class AreaServiceImpl implements AreaService {

    @Resource
    protected AreaDao areaDao;

    @Resource
    SynXunfeiService synXunfeiService;

    @Override
    public AreaResp queryArea(Long id) {
        log.info("AreaServiceImpl queryArea id={}", id);
        Area area = areaDao.selectById(id);
        if (null == area) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "校区");
        }
        AreaResp areaResp = new AreaResp();
        BeanUtil.copyProperties(area, areaResp);
        return areaResp;
    }

	@Override
	public List<AreaResp> queryAreaList(Long partyId) {
		log.info("AreaServiceImpl queryAreaList partyId={}", partyId);
		List<Area> areaList = this.areaDao.selectList(Wrappers.lambdaQuery(Area.class)
				.eq(Area::getPartyId, partyId)
				.orderByAsc(Area::getSort));
		List<AreaResp> returnList = BeanUtil.copyList(areaList, AreaResp.class);
		return returnList;
	}

    @Override
    public IPage<AreaResp> queryList(QueryAreaReq queryRequest) {
        log.info("AreaBOImpl queryList queryRequest={}", queryRequest);
        IPage<AreaResp> result = new Page<>();
        result.setCurrent(queryRequest.getPageNo());
        result.setPages(queryRequest.getPageSize());

        LambdaQueryWrapper<Area> queryAreaWrapper = new LambdaQueryWrapper<>();
        queryAreaWrapper.eq(ObjectUtils.isNotNull(queryRequest.getPartyId()), Area::getPartyId, queryRequest.getPartyId());

        IPage<Area> page = areaDao.selectPage(new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize()), queryAreaWrapper);
        return page.convert(u -> {
            AreaResp v = new AreaResp();
            BeanUtils.copyProperties(u, v);
            return v;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(AddAreaReq addRequest) {
        log.info("AreaBOImpl save request={}", addRequest);
        Area area = new Area();
        BeanUtil.copyProperties(addRequest, area);
        area.setCreateTime(new Date());
        int i = 0;
        try {
            Integer sort=areaDao.findMaxSort(addRequest.getPartyId());
            if(null == sort){
                sort =1;
            }else {
                sort++;
            }
            area.setSort(sort);
            i = areaDao.insert(area);
            SchoolAreaResp schoolAreaResp=new SchoolAreaResp();
            schoolAreaResp.setId(area.getSchoolId().toString());
            schoolAreaResp.setName(area.getAreaName());
            synXunfeiService.pushDate(schoolAreaResp, XunFeiPushEventApiService.EVENT_CAMPUS,XunFeiPushEventApiService.INSERT,area.getPartyId().toString(),area.getCreateUserId().toString());
        } catch (Exception e) {
            log.info("AreaBOImpl add e={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(UpdateAreaReq updateRequest) {
        log.info("AreaServiceImpl update request={}", updateRequest);
        Area db =areaDao.selectById(updateRequest.getSchoolId());
        if(null == db){
            throw new BizException("校区不存在");
        }
        if(!db.getPartyId().equals(updateRequest.getUpdatePartyId())){
            throw new BizException("无此数据权限");
        }
        Area update=new Area();
        BeanUtil.copyProperties(updateRequest,update);
        update.setUpdateUserId(updateRequest.getUpdateUserId());
        update.setUpdateTime(new Date());
        int i = 0;
        try {
            i = areaDao.updateById(update);
            SchoolAreaResp schoolAreaResp=new SchoolAreaResp();
            schoolAreaResp.setId(update.getSchoolId().toString());
            schoolAreaResp.setName(update.getAreaName());
            synXunfeiService.pushDate(schoolAreaResp, XunFeiPushEventApiService.EVENT_CAMPUS,XunFeiPushEventApiService.UPDATE,db.getPartyId().toString(),updateRequest.getUpdateUserId().toString());
        } catch (Exception e) {
            log.info("AreaServiceImpl add e={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id,Long partyId) {
        log.info("AreaServiceImpl delete id={}", id);
        Area db =areaDao.selectById(id);
        if(!db.getPartyId().equals(partyId)){
            throw new BizException("无此数据权限");
        }
        SchoolAreaResp schoolAreaResp=new SchoolAreaResp();
        schoolAreaResp.setId(db.getSchoolId().toString());
        schoolAreaResp.setName(db.getAreaName());
        synXunfeiService.pushDate(schoolAreaResp, XunFeiPushEventApiService.EVENT_CAMPUS,XunFeiPushEventApiService.DELETE,db.getPartyId().toString(),db.getCreateUserId().toString());
        return areaDao.deleteById(id);
    }

}
